<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>多文件上传与预览</title>
    <script th:src="@{/jquery-3.7.1.js}" type="application/javascript"></script>
    <style>
        #previewContainer img {
            max-width: 200px;
            margin: 5px;
        }
    </style>
</head>
<body>
<h1>多文件上传与预览</h1>
<hr>

<!-- 文件上传表单 -->
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
    选择文件 :<br>
    <input type="file" name="files" id="fileInput" multiple accept="image/*" /><br>
    <div id="previewContainer"></div>
    <input type="submit" value="上传文件" />
</form>

<script>
    $(document).ready(function() {
        // 监听文件输入框的变化
        $('#fileInput').on('change', function(e) {
            var files = this.files;
            if (files.length > 0) {
                var previewContainer = $('#previewContainer');
                previewContainer.empty(); // 清空之前的预览图片

                for (var i = 0; i < files.length; i++) {
                    var file = files[i];

                    if (file.type.match('image.*')) { // 只预览图像文件
                        var reader = new FileReader();

                        // 当文件读取完成时，显示预览图
                        reader.onload = function(e) {
                            var img = $('<img />').attr('src', e.target.result);
                            previewContainer.append(img);
                        };

                        // 读取文件为DataURL格式
                        reader.readAsDataURL(file);
                    }
                }
            }
        });
    });
</script>
</body>
</html>